<template>
  <div class="pro_container">
    <div class="pro_content">
      <div class="title">
        <span>工程项目管理</span>
      </div>
      <div class="function">
        <a-button @click="addData">添加</a-button>
        <!-- 添加事件弹出框 -->
        <a-modal
          cancelText="取消"
          okText="确定"
          title="添加工程"
          :visible="addVisible"
          @ok="addHandleOk"
          @cancel="addHandleCancel"
        >
          <div class="addContainer">
            <a-form-model
              :model="projectForm"
              :rules="projectFormRules"
              ref="projectFormRef"
              :label-col="{ span: 4 }"
              :wrapper-col="{ span: 18 }"
            >
              <a-form-model-item prop="name" label="工程名称">
                <a-input v-model="projectForm.name" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item prop="project_models" label="工程模型">
                <a-tree-select
                  v-model="projectForm.project_models"
                  :value="projectForm.project_models"
                  multiple
                  tree-data-simple-mode
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="modelTreeData"
                  placeholder="Please select"
                  :load-data="onLoadDataModel"
                />
              </a-form-model-item>
              <a-form-model-item prop="project_inputs" label="输入文件">
                <a-tree-select
                  v-model="projectForm.project_inputs"
                  :value="projectForm.project_inputs"
                  multiple
                  tree-data-simple-mode
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="inputsTreeData"
                  placeholder="Please select"
                  :load-data="onLoadDataFile"
                />
              </a-form-model-item>
            </a-form-model>
          </div>
        </a-modal>
        <a-input
          v-model="searchText"
          @change="searchChange"
          placeholder="请输入关键字"
        >
          <a-icon slot="prefix" type="search" />
        </a-input>
      </div>
      <div class="table">
        <!-- 表头元素 -->
        <a-table
          :columns="columns"
          :data-source="data"
          rowKey="id"
          :pagination="{ pageSize: 9 }"
        >
          <span slot="name" slot-scope="text, record" v-html="record.name">{{
            record.name
          }}</span>
          <span slot="project_models" slot-scope="text, record">{{
            record.project_models
          }}</span>
          <span slot="project_inputs" slot-scope="text, record">{{
            record.project_inputs
          }}</span>
          <!-- <template slot="project_inputs" slot-scope="text, record">
            <span v-for="(item,index) in record.project_inputs" :key="index">{{item}}--</span>
          </template>-->
          <span
            slot="founder"
            slot-scope="text, record"
            v-html="record.founder"
            >{{ record.founder }}</span
          >
          <span
            slot="time"
            slot-scope="text, record"
            v-html="record.currentTime"
            >{{ record.currentTime }}</span
          >
          <span slot="handle" slot-scope="text, record, index">
            <a-tooltip placement="topLeft" title="编辑">
              <img
                @click="edit(record, index)"
                class="editImg"
                src="../../../assets/images/edit.png"
                alt="编辑"
              />
            </a-tooltip>
            <!-- 编辑事件弹出框 -->
            <a-modal
              title="修改工程"
              cancelText="取消"
              okText="确定"
              :visible="editVisible"
              @ok="editHandleOk"
              @cancel="editHandleCancel"
            >
              <div class="addContainer">
                <a-form-model
                  :model="projectForm"
                  :rules="projectFormRules"
                  ref="projectFormRef"
                  :label-col="{ span: 4 }"
                  :wrapper-col="{ span: 18 }"
                >
                  <a-form-model-item prop="name" label="工程名称">
                    <a-input v-model="projectForm.name" placeholder="请输入" />
                  </a-form-model-item>
                  <a-form-model-item prop="project_models" label="工程模型">
                    <a-tree-select
                      v-model="projectForm.project_models"
                      :value="projectForm.project_models"
                      multiple
                      tree-data-simple-mode
                      style="width: 100%"
                      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                      :tree-data="modelTreeData"
                      placeholder="Please select"
                      :load-data="onLoadDataModel"
                    />
                  </a-form-model-item>
                  <a-form-model-item prop="project_inputs" label="输入文件">
                    <a-tree-select
                      v-model="projectForm.project_inputs"
                      :value="projectForm.project_inputs"
                      multiple
                      tree-data-simple-mode
                      style="width: 100%"
                      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                      :tree-data="inputsTreeData"
                      placeholder="Please select"
                      :load-data="onLoadDataFile"
                    />
                  </a-form-model-item>
                </a-form-model>
              </div>
            </a-modal>
            <a-tooltip placement="topLeft" title="删除">
              <img
                @click="del(record)"
                class="deleteImg"
                src="../../../assets/images/delete.png"
                alt="删除"
              />
            </a-tooltip>
            <!-- 删除事件弹出框 -->
            <a-modal
              title="确认删除"
              cancelText="取消"
              okText="确定"
              :visible="delVisible"
              @ok="delHandleOk"
              @cancel="delHandleCancel"
            >
              <p class="deleteText">
                <i class="iconfont icon-zhiwei-quanbuzhiwei"></i>
                确认删除{{ delName }}?
              </p>
            </a-modal>
          </span>
        </a-table>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getAllProInfo,
  addProject,
  editProject,
  delProject
} from '../../../api/project'
import {
  getAllModuleInfo,
  getModelInfo,
  getFile
} from '../../../api/moduleInfo'
import { getUserInfo } from '../../../api/admin'
const columns = [
  {
    title: '工程名称',
    dataIndex: 'name',
    key: 'name',
    ellipsis: true
  },
  {
    title: '创建人',
    dataIndex: 'founder',
    key: 'founder',
    ellipsis: true
  },
  {
    title: '创建时间',
    dataIndex: 'currentTime',
    scopedSlots: { customRender: 'currentTime' },
    ellipsis: true
  },
  {
    title: '工程模型',
    dataIndex: 'project_models',
    key: 'project_models',
    ellipsis: true
  },
  {
    title: '输入文件',
    dataIndex: 'project_inputs',
    key: 'project_inputs',
    ellipsis: true
  },
  {
    title: '操作',
    dataIndex: 'handle',
    scopedSlots: { customRender: 'handle' }
  }
]
export default {
  data() {
    return {
      data: [],
      columns,
      selectData: [],

      // 搜索
      searchText: '',
      searchData: [],

      // 删除
      delId: '',
      delName: '',
      delFounderId: '',
      delVisible: false,

      // 添加
      // 树形选择框
      inputsTreeData: [],
      modelTreeData: [],
      // selectId: '请选择',
      addVisible: false,
      projectForm: {
        name: '',
        department: '',
        project_inputs: [],
        project_models: [],
        model_ids: [],
        input_ids: [],
        founder: '',
        currentTime: '',
        founder_id: '',
        operator_id: ''
      },
      projectFormRules: {
        name: [{ required: true, message: '工程名称不能为空', tigger: 'blur' }],
        project_models: [
          {
            required: true,
            message: '工程模型不能为空',
            tigger: 'blur',
            type: 'array'
          }
        ],
        project_inputs: [
          {
            required: true,
            message: '输入文件不能为空',
            tigger: 'blur',
            type: 'array'
          }
        ]
      },

      // 下拉列表
      allModuleInfo: [],

      // 修改
      editVisible: false,
      editIndex: 0
    }
  },
  created() {
    this.getProject()
  },
  methods: {
    // 获取所有工程项目信息
    getProject() {
      const vm = this
      getAllProInfo().then((res) => {
        console.log('res', res)
        if (res.code === 200) {
          vm.data = JSON.parse(JSON.stringify(res.data))
          vm.data.map((item) => {
            vm.getCTime(item)
            item.id = item._id
          })
          vm.selectData = JSON.parse(JSON.stringify(vm.data))

          for (let i = 0; i < vm.data.length; i++) {
            if (vm.data[i].project_inputs !== null) {
              vm.data[i].project_inputs = vm.selectData[i].project_inputs
                .map((item) => {
                  return item.name
                })
                .toString()
            }
            if (vm.data[i].project_models !== null) {
              vm.data[i].project_models = vm.data[i].project_models
                .map((item) => {
                  return item.name
                })
                .toString()
            }
          }
          vm.searchData = JSON.parse(JSON.stringify(vm.data))
        }
      })
    },
    // 表格的添加事件
    getTreeData() {
      const vm = this
      // 请求模块信息
      getAllModuleInfo().then((res) => {
        for (let i = 0; i < res.data.length; i++) {
          res.data[i].title = res.data[i].name
          res.data[i].value = res.data[i]._id
          res.data[i].id = res.data[i]._id
        }
        vm.modelTreeData = JSON.parse(JSON.stringify(res.data))
        vm.inputsTreeData = JSON.parse(JSON.stringify(res.data))
      })
    },
    onLoadDataFile(treeNode) {
      const vm = this
      // 获取所有模块信息(选择列表)
      // treeNode点击对应的数组
      return new Promise((resolve) => {
        const id = treeNode.dataRef.id
        // 根据模块ID查找对应输入文件
        getFile(id).then((res) => {
          if (res.data !== null) {
            for (let i = 0; i < res.data.length; i++) {
              // 组件必须使用id,title,value三个属性,否则不对
              res.data[i].title = res.data[i].name
              res.data[i].value = res.data[i]._id
              res.data[i].id = res.data[i]._id
              res.data[i].isLeaf = true
            }
            treeNode.dataRef.children = JSON.parse(JSON.stringify(res.data))
            vm.inputsTreeData = JSON.parse(
              JSON.stringify([...vm.inputsTreeData])
            )
          } else {
            vm.$message.info('该模块下没有任何输入文件!')
            treeNode.dataRef.isLeaf = true
            vm.inputsTreeData = JSON.parse(
              JSON.stringify([...vm.inputsTreeData])
            )
          }
          resolve()
          // ... 将数组展开,es6
        })
      })
    },
    onLoadDataModel(treeNode) {
      const vm = this
      return new Promise((resolve) => {
        // 获取所有模块信息(选择列表)
        // treeNode点击对应的数组
        const id = treeNode.dataRef.id
        console.log('vmvmvmvmvmvvmvmvm', treeNode.dataRef.id)
        // 根据模块ID查找对应模型信息
        getModelInfo(id).then((res) => {
          console.log('resresresresrsesrsers')
          if (res.data !== null) {
            for (let i = 0; i < res.data.length; i++) {
              // 组件必须使用id,title,value三个属性,否则不对
              res.data[i].title = res.data[i].name
              res.data[i].value = res.data[i]._id
              res.data[i].id = res.data[i]._id
              res.data[i].isLeaf = true
            }
            treeNode.dataRef.children = JSON.parse(JSON.stringify(res.data))
            vm.modelTreeData = JSON.parse(JSON.stringify([...vm.modelTreeData]))
          } else {
            vm.$message.info('该模块下没有任何三维模型!')
            treeNode.dataRef.isLeaf = true
            vm.modelTreeData = JSON.parse(JSON.stringify([...vm.modelTreeData]))
          }
          // ... 将数组展开,es6
          resolve()
        })
      })
    },
    addData() {
      this.projectForm.name = ''
      this.projectForm.project_models = null
      this.projectForm.project_inputs = null
      // 获取所有模块信息(选择列表)
      this.getTreeData()
      this.addVisible = true
    },
    addHandleCancel() {
      this.addVisible = false
      console.log(
        'selectIddddddddddddddddddddddddddddddaaaaaddddddddddddddddd',
        this.projectForm
      )
    },
    addHandleOk() {
      const vm = this

      vm.$refs.projectFormRef.validate((valid) => {
        if (!valid) return
        // 页面伪添加操作
        // 获取创建人名字和ID
        const userId = JSON.parse(sessionStorage.getItem('data')).data.user_id
        vm.projectForm.founder_id = userId
        getUserInfo(userId).then((res) => {
          if (res.code === 200) {
            vm.projectForm.founder = res.data.username
            vm.projectForm.department = res.data.department
          }
        })
        vm.projectForm.model_ids = vm.projectForm.project_models.toString()
        vm.projectForm.input_ids = vm.projectForm.project_inputs.toString()
        const addForm = {}
        addForm.name = vm.projectForm.name
        addForm.founder_id = vm.projectForm.founder_id
        addForm.department = vm.projectForm.department
        addForm.model_ids = vm.projectForm.project_models
        addForm.input_ids = vm.projectForm.project_inputs
        // 异步添加操作
        addProject(addForm).then((res) => {
          if (res.code === 200) {
            vm.getProject()
            vm.searchChange()
            vm.$message.success('添加成功')
          }
        })
        this.addVisible = false
      })
    },
    // 表格的编辑事件
    edit(record, index) {
      this.getTreeData()
      this.editVisible = true
      this.editIndex = index
      this.projectForm = JSON.parse(JSON.stringify(record))
      const inputs = this.projectForm.project_inputs
      const models = this.projectForm.project_models
      if (inputs !== null) {
        this.projectForm.project_inputs = inputs.split(',')
      }
      if (inputs !== null) {
        this.projectForm.project_models = models.split(',')
      }
    },
    editHandleOk() {
      const vm = this
      vm.$refs.projectFormRef.validate((valid) => {
        if (!valid) return

        // 获取创建人
        const userId = JSON.parse(sessionStorage.getItem('data')).data.user_id
        vm.projectForm.operator_id = userId
        if (vm.projectForm.operator_id !== vm.projectForm.founder_id) {
          vm.$message.error('操作失败!您没有权限进行此项操作!')
        } else {
          // 从初始请求到的工程项目信息的数组中筛选出当前编辑id的一项
          vm.tmpSelectData = vm.selectData.filter((item) => {
            return item.id === vm.projectForm.id
          })
          // 从筛选出的这项中继续进行筛选,筛选编辑后选择框中剩下的选中的id
          vm.projectForm.model_ids = vm.tmpSelectData[0].project_models.filter(
            (item) => {
              const tmpArr = vm.projectForm.project_models
              for (let i = 0; i < tmpArr.length; i++) {
                if (item.name === tmpArr[i]) {
                  tmpArr.splice(i, 1)
                  return item._id
                }
              }
            }
          )
          vm.projectForm.input_ids = vm.tmpSelectData[0].project_inputs.filter(
            (item) => {
              const tmpArr = vm.projectForm.project_inputs
              for (let i = 0; i < tmpArr.length; i++) {
                if (item.name === tmpArr[i]) {
                  tmpArr.splice(i, 1)
                  return item._id
                }
              }
            }
          )
          vm.projectForm.model_ids = vm.projectForm.model_ids.map(
            (item) => item._id
          )
          vm.projectForm.model_ids = vm.projectForm.project_models.concat(
            vm.projectForm.model_ids
          )
          vm.projectForm.input_ids = vm.projectForm.input_ids.map(
            (item) => item._id
          )
          vm.projectForm.input_ids = vm.projectForm.project_inputs.concat(
            vm.projectForm.input_ids
          )
          const editForm = {}
          editForm.name = vm.projectForm.name
          editForm.founder_id = vm.projectForm.founder_id
          editForm.department = vm.projectForm.department
          // editForm.model_ids = vm.projectForm.model_ids
          // 去重
          editForm.model_ids = [...new Set(vm.projectForm.model_ids)]
          editForm.input_ids = [...new Set(vm.projectForm.input_ids)]
          // editForm.input_ids = vm.projectForm.input_ids
          editProject(vm.projectForm.id, editForm).then((res) => {
            if (res.code === 200) {
              vm.getProject()
              vm.searchChange()
              vm.$message.success('修改成功')
            }
          })
        }
        vm.editVisible = false
      })
    },
    editHandleCancel() {
      this.editVisible = false
    },
    // 表格的删除事件
    del(record) {
      this.delFounderId = record.founder_id
      this.delId = record.id
      this.delName = record.name
      this.delVisible = true
      console.log('key', record.id)
    },
    delHandleOk() {
      const vm = this
      const operatorId = JSON.parse(sessionStorage.getItem('data')).data.user_id
      if (operatorId !== vm.delFounderId) {
        vm.$message.error('操作失败!您没有权限进行此项操作!')
      } else {
        const data = vm.data.filter((item) => item.id !== vm.delId)
        vm.data = data
        delProject(vm.delId).then((res) => {
          if (res.code === 200) {
            vm.getProject()
            vm.searchChange()
            console.log('delres', res)
            vm.$message.success('删除成功')
          }
        })
      }
      vm.delVisible = false
    },
    delHandleCancel() {
      this.delVisible = false
    },
    // 获取当前时间
    getCTime(item) {
      const time = new Date(item.ctime * 1000)
      const y = time.getFullYear()
      const m = time.getMonth() + 1
      const d = time.getDate()
      const h = time.getHours()
      const mm = time.getMinutes()
      const s = time.getSeconds()
      item.currentTime =
        y +
        '-' +
        this.add0(m) +
        '-' +
        this.add0(d) +
        ' ' +
        this.add0(h) +
        ':' +
        this.add0(mm) +
        ':' +
        this.add0(s)
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },

    // 搜索
    // 搜索框输入内容变化时触发
    searchChange() {
      console.log(this.searchText, 'searchText')
      const vm = this
      let value = this.searchText
      value = value.trim()
      const tmpData = JSON.parse(JSON.stringify(vm.searchData))
      console.log('tmpData', tmpData)
      vm.data = tmpData.filter(
        (item) =>
          String(item.name).includes(value) ||
          String(item.founder).includes(value) ||
          String(item.currentTime).includes(value) ||
          String(item.project_inputs).includes(value) ||
          String(item.project_models).includes(value)
      )
      console.log(' vm.searchData', vm.data)
    }
  }
}
</script>
<style>
.pro_container {
  height: 100%;
  width: 100%;
  padding: 31px 32px;
  /* background-color: blue; */
  background-color: rgba(246, 246, 250);
}
.pro_container .pro_content {
  height: 100%;
  width: 100%;
  padding-top: 24px;
  z-index: 7;
  background: #ffffff;
  box-shadow: 0px 10px 21px rgba(3, 57, 165, 0.08);
  border-radius: 12px;
}
/* 标题 最左上角的 */
.pro_content .title {
  margin-left: 36px;
  font: bold 20px 'PingFang SC';
}
/* 第二行的按钮和搜索框 */
.pro_content .function {
  display: flex;
  justify-content: space-between;
  margin-top: 24px;
  padding: 0 36px;
}
/* 第二行按钮 */
.pro_content .function .ant-btn {
  height: 35px;
  width: 100px;
  color: #ffffff;
  font: bold 16px 'PingFang SC';
  background-color: #2c5bb9;
  border-color: #2c5bb9;
  box-shadow: 0px 7px 14px rgba(44, 91, 185, 0.47);
}
/* 第二行输入框 */
.function .ant-input-affix-wrapper .ant-input {
  border: 1px solid #2c5bb9;
}
.function .ant-input-prefix .anticon {
  font-size: 18px;
  color: #8f97a8;
}
.ant-input-affix-wrapper .ant-input-prefix {
  left: 6px;
}
.pro_content .function .ant-input-affix-wrapper {
  height: 35px;
  width: 293px;
}
/* 表格 */
.pro_content .table {
  margin-top: 25px;
}
/* 分页页数样式 */
.pro_content .ant-pagination-item a,
.pro_content .ant-pagination-disabled a {
  color: #8f97a8;
}
.pro_content .ant-pagination-next .ant-pagination-item-link:hover,
.pro_content .ant-pagination-prev .ant-pagination-item-link:hover {
  border-color: #4c72bd;
  color: #4c72bd;
}
.pro_content .ant-pagination-item,
.pro_content .ant-pagination-prev .ant-pagination-item-link,
.pro_content .ant-pagination-next .ant-pagination-item-link {
  border-color: #8f97a8;
}
.pro_content .ant-pagination .ant-pagination-item-active a {
  color: #fff;
}
.pro_content .ant-pagination .ant-pagination-item-active {
  background-color: #4c72bd;
  border-color: #4c72bd;
}
/* 表格行hover */
.pro_content .ant-table-body .ant-table-tbody .ant-table-row:hover td {
  background-color: #f2f7fa;
}
/* 操作删除编辑按钮 */
.ant-table {
  font-size: 16px;
  color: #575c66;
}
.pro_content .table .deleteImg {
  margin-left: 34px;
  height: 22px;
  width: 17px;
  cursor: pointer;
}
.pro_content .table .editImg {
  height: 23px;
  width: 23px;
  cursor: pointer;
}
.deleteText {
  font-size: 16px;
}
.icon-zhiwei-quanbuzhiwei {
  font-size: 16px;
  color: #0339a5;
}
.ant-modal-title {
  color: #fff;
}
/* 弹出框表头 修改默认组件需要全局样式才能完成修改 */
.ant-modal-header {
  background-color: #0339a5;
}
.ant-modal-footer .ant-btn {
  border: 1px solid #2c5bb9;
}
.ant-modal-footer .ant-btn-primary {
  background-color: #2c5bb9;
}
.ant-table-tbody tr td:first-child {
  padding-left: 35px;
}
.ant-table-thead tr th:first-child {
  padding-left: 35px;
}
.ant-table-tbody tr td:last-child {
  display: flex;
  padding: 16px 0px 16.5px 16px;
}
/* 表头颜色*/
.ant-table-column-title {
  font: bold 18px 'PingFang SC';
  color: #142c5c;
}
.ant-table-content .ant-table-body .ant-table-thead > tr > th {
  background-color: rgba(229, 235, 247, 1);
}
.ant-form-item-required::before {
  display: none;
}
</style>
